package com.qf.controller;

import com.qf.util.UploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/*
杨威
2021/9/17
21:46
*/
@WebServlet("/upload")
@MultipartConfig
public class UploadController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Part part = request.getPart("file");
        String fileName = part.getSubmittedFileName();
        boolean check = UploadUtil.check(fileName);
        if(!check){
            response.getWriter().write("文件格式错误！");
            return;
        }
        String filePath=request.getServletContext().getRealPath("/WEB-INF/upload");
        String newFilePath = UploadUtil.creatNewFilePath(filePath, fileName);
        String newFileName = UploadUtil.creatNewFileName(fileName);
        File file=new File(newFilePath);
        if(!file.exists()){
            file.mkdirs();
        }
        part.write(newFilePath+File.separator+newFileName);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
